const express = require('express')
const path = require('path')
// const router = require('./router.js')
const api = require('./api')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const expressJWT = require('express-jwt')
const config = require('./config')

//连接数据库
mongoose.connect('mongodb://localhost/blog', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, function (err, db) {
    if(err){
        console.log(err)
    }
    console.log('mongodb is connected.')
})
// express实例
const app = express()
// 跨域设置
app.all('/*', function(req, res, next) {
    // CORS headers
    res.header("Access-Control-Allow-Origin", "*") // restrict it to the required domain
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    // Set custom headers for CORS
    res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key,Authorization')
    if (req.method == 'OPTIONS') {
      res.status(200).end()
    } else {
      next()
    }
})
// token 验证
app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {   
    res.status(401).send('invalid token...')
  }
  next()
})
// expressJWT定义token验证接口
app.use(expressJWT({secret: config.session.secrets,  getToken: function fromHeaderOrQuerystring (req) {
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
      return req.headers.authorization.split(' ')[1];
  } else if (req.query && req.query.token) {
      return req.query.token;
  } else if (req.body && req.body.token) {
      return req.body.token;
  }
  return null;
}}).unless({path: ["/login"]}))
// 向外暴露文件
// app.use(express.static('./dist'))
// app.use(express.static(path.join(__dirname,'dist')))
// post请求解析中间件
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())
//路由挂载到app中
// app.use(router)
app.use(api)
// 监听端口
app.listen(4000,()=>{
    console.log('server is running at por 4000...')
})